package com.zlx.store.user.AOP;

import com.zlx.store.common.constant.RespCode;
import com.zlx.store.common.results.HttpResp;
import com.zlx.store.domain.entity.Coupon;
import com.zlx.store.domain.entity.CouponRelateUser;
import com.zlx.store.domain.entity.User;
import com.zlx.store.user.dao.CouponDao;
import com.zlx.store.user.dao.CouponRelateUserDao;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
public class CouponCreator {
    @Autowired
    private CouponRelateUserDao couponRelateUserDao;
    @Autowired
    private CouponDao couponDao;

    @Pointcut("@annotation(com.zlx.store.common.annotation.CreateCouponAnno)")
    private void annotationPointCut() {
    }

    @Around("annotationPointCut()")
    private HttpResp sendCoupon(ProceedingJoinPoint pjp) throws Throwable {
        HttpResp resp = (HttpResp) pjp.proceed();
        if (resp.getRespCode().equals(RespCode.USER_REGISTER_SUCCESS)) {
            User user = (User) pjp.getArgs()[0];
            Coupon coupon = couponDao.selectById(0);
            CouponRelateUser couponRelateUser = new CouponRelateUser(null, user.getUserId(), coupon.getCouponId(), 1);
            couponRelateUserDao.insert(couponRelateUser);
        }
        return HttpResp.httpResp(RespCode.USER_REGISTER_SUCCESS, null, new Date());
    }
}
